package com.wuhongyu.service.impl;

import com.wuhongyu.base.BaseServiceImpl;
import com.wuhongyu.common.MyCommon;
import com.wuhongyu.entity.Product;
import com.wuhongyu.repository.ProductDao;
import com.wuhongyu.service.ProductService;
import com.wuhongyu.util.MyUtil;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;

@Service("productService")
public class ProductServiceImpl extends BaseServiceImpl<Product> implements ProductService {

    private ProductDao productDao;
    @Resource
    public void setDao(ProductDao productDao){
        super.setBaseDao(productDao);
        this.productDao = productDao;
    }


    @Override
    public Page<Product> findAll(Product product, Integer number) {
        Specification<Product> spec = (root,query,cb) ->{
            List<Predicate> list = new ArrayList<>();
            if(MyUtil.notEmpty(product.getName()))
                list.add(cb.like(root.get("name"),"%"+product.getName()+"%"));
            if(MyUtil.notEmpty(product.getVersion()))
                list.add(cb.like(root.get("version"),"%"+product.getVersion()+"%"));
            if(MyUtil.notEmpty(product.getBatch()))
                list.add(cb.like(root.get("batch"),"%"+product.getBatch()+"%"));
            return cb.and(list.toArray(new Predicate[list.size()]));
        };
        return productDao.findAll(spec,new PageRequest(MyUtil.getCurrentPage(number),MyCommon.PAGESIZE));
    }

}